﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;

using System.Diagnostics;
namespace Pdf2ImageProcess
{

    public delegate int Pdf2JpgCallBack(int nMin, int nMax, int nCur);

    class PDFThread
    {
        [DllImport("PDFToX.dll")]
        private static extern int OpenPDF(string szPDFFileName, string szPWD);
        [DllImport("PDFToX.dll")]
        private static extern int ClosePDF(int hPDF);
        [DllImport("PDFToX.dll")]
        private static extern int GetPageNum(int hPDF);
        [DllImport("PDFToX.dll")]
        private static extern int ExportIMG(int hPDF, string szDir, string szPrefix,
                    int nFormatA, int dpiX, int dpiY, int nFrom, int nTo, Pdf2JpgCallBack pfun);
        [DllImport("PDFtoX.dll", EntryPoint = "SetRCPath")]
        private static extern int SetRCPath(string rcPath);

        /*[DllImport("RecogOcr.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern int SavePDFPage(int nPage, int nDpi, [MarshalAs(UnmanagedType.LPWStr)] string szFileName);
        [DllImport("PDFLoad.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern int OpenPDF([MarshalAs(UnmanagedType.LPWStr)] string szFileName);
        */

        public bool pdf2Image(string filePath,string guid)
        {
            InitSrcpath();
            try
            {
                return ReadPDF2JPG(filePath, guid);
            }
            catch (Exception ex)
            {
                writelog("guid:" + guid + "PDF转图片异常!!!" + ex.ToString());
            }
            return false;
        }

        private void writelog(string logcontent)
        {
            if (logcontent.Length <= 0) return;
            LocalLog.GetInstance().Write(logcontent);
        }
        private static string TempPath = System.AppDomain.CurrentDomain.BaseDirectory + "Temp\\";

        private void InitSrcpath()
        {
            //防止转换后乱码，设置解晰路径
            string strRcPath = System.AppDomain.CurrentDomain.BaseDirectory;
            if (!strRcPath.EndsWith("\\"))
            {
                strRcPath += "\\RC";
            }
            //MessageBox.Show(strRcPath);
            SetRCPath(strRcPath);
            writelog("设置RC路径:" + strRcPath);
        }
        public void InitDir(string dirName)
        {
            try
            {
                string TempPathRects = TempPath + dirName + "\\Rects\\";
                string TempPathScanned = TempPath + dirName + "\\Scanned\\";
                if (!Directory.Exists(TempPathRects))
                {
                    Directory.CreateDirectory(TempPathRects);
                }
                if (!Directory.Exists(TempPathScanned))
                {
                    Directory.CreateDirectory(TempPathScanned);
                }
            }
            catch (Exception e)
            {
                writelog("InitDir" + dirName + "出现异常" + e.ToString());
            }
        }
        public static int Report(int nMin, int nMax, int nCur)
        {
            return 1;
        }
        private bool ReadPDF2JPG(string m_pdfpath, string guid)
        {
            writelog("ReadPDF2JPG guid:" +guid);
            string TempPathRects = TempPath + guid + "\\Rects\\";
            string TempPathScanned = TempPath + guid + "\\Scanned\\";
            InitDir(guid);
            int pagecount = 0;
            int hPDF = OpenPDF(m_pdfpath, "");
            if (hPDF <= 0)
            {
                writelog("pdf可能存在异常,打开pdf失败" + m_pdfpath);
                return false;
            }
            pagecount = GetPageNum(hPDF);
            if (pagecount <= 0)
            {
                writelog("pdf页数为0" + guid);
                return false;
            }
            Pdf2JpgCallBack myCallBack = new Pdf2JpgCallBack(Report);
            int ret = ExportIMG(
                        hPDF,           //PDF文件句柄 
                        TempPathScanned,    //目标路径
                        "0",          //生成的文件名前缀，Pre00001.jpg
                        2,              //文件格式 BMP：1，JPG：2，TIF：3，PNG：4，GIF：5，PCX：6，TGA：7
                        200,             //图像分辨率，常用的是72或96，但一般不能超过1000
                        200,             //图像分辨率，常用的是72或96，但一般不能超过1000
                        1,          //要转换的起始页
                        pagecount,            //要转换的终止页
                        myCallBack      //回调函数
                        );
            //if (ret <= 0)//返回0也代表成功
            // {
            //     writelog("该页pdf转换失败!!"+Global.g_guid);
            //     return;
            //  }
            if (hPDF > 0) ClosePDF(hPDF);
            /*int pagecount = OpenPDF(m_pdfpath);
            if (pagecount == 0)
            {
                writelog(m_pdfpath + " 总页码为0，可能是文件损坏");
                return;
            }
            for (int i = 0; i < pagecount && Global.servicePdfThread; i++)
            {
                if (SavePDFPage(i, 200, TempPathScanned + (i + 1).ToString("D5") + ".jpg") == 0)
                {
                    writelog("guid:" + Global.g_guid +"pdf转换图片失败!!\r\n");
                    return;
                }
            }*/
            writelog("guid:" + guid + "pdf " + pagecount.ToString()+ "页全部转换为图\r\n");
            return true;
        }
    }
}